package com.lkd.handler;
import com.google.common.collect.Lists;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *接收售货机传来的信息,并自动创建维修工单
 */
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VmStatusMsgHandler implements MsgHandler {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        if (StringUtils.isEmpty(jsonMsg)) {
            return;
        }
        /**
         * 解析emq传来的消息,反序列化成java对象
         */
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null) {
            return;
        }

        vmStatusContract.getStatusInfo().forEach(statusInfo->{
            if (!statusInfo.isStatus()) {
                TaskViewModel taskViewModel = new TaskViewModel();
                taskViewModel.setCreateType(0);
                taskViewModel.setInnerCode(vmStatusContract.getInnerCode()); //设备编号
                /**
                 * 这里需要查询手上工单数量最少的运维人员
                 */
                Integer userId = findMinTaskCountUser(taskViewModel);
                taskViewModel.setUserId(userId);
                taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR); //维修类型工单
                taskViewModel.setDesc(vmStatusContract.getInnerCode()+"号设备出现故障,需要维修"); //备注
                taskService.saveTask(taskViewModel);
            }
        });
    }


    /**
     * 查询手上工单最少的用户信息
     * @param taskViewModel
     * @return
     */
    private Integer findMinTaskCountUser(TaskViewModel taskViewModel) {
        //任务执行时间
        String format = new SimpleDateFormat("yyyyMMdd").format(new Date());

        //获取任务执行区域
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());

        String roleCode = "1002"; //运营人员编号
        if (taskViewModel.getProductType() != VMSystem.TASK_TYPE_SUPPLY) {
            roleCode = "1003"; //运维人员编号
        }

        String key = VMSystem.REGION_TASK_KEY_PREF + format + "." + vmInfo.getRegionId() + "." + roleCode;

        /**
         *取出最上面的那个值,也就是最小的值
         */
        Integer userId = (Integer) redisTemplate.opsForZSet().range(key, 0, 1)
                                                .stream().findFirst().get();
        log.info("userid:{}",userId);
        return userId;
    }
//    private Integer findMinTaskCountUser(String innerCode) {
//        //查询所有负责改售货机维护的维修人员列表
//        List<UserVO> userVOList = userService.getRepairerListByInnerCode(innerCode);
//
//        if (CollectionUtils.isEmpty(userVOList)) {
//            throw new LogicException("该区域没有运维人员");
//        }
//
//        //查询当天每个维修人员的工单数量
//        DateTime begin = DateUtil.beginOfDay(new Date());
//        DateTime end = DateUtil.endOfDay(new Date());
//        List<TaskEntity> taskEntityList = taskService.getUserTask(begin, end);
//
//        Map<Integer, List<TaskEntity>> userCount = taskEntityList.stream().collect(Collectors.groupingBy(TaskEntity::getUserId));
//
//        List<UserTaskCountVo> countVoList = userVOList.stream().map(userVO -> {
//
//            UserTaskCountVo userTaskCountVo = new UserTaskCountVo();
//            userTaskCountVo.setUserId(userVO.getUserId());
//
//            List<TaskEntity> taskList = userCount.get(userVO.getUserId());
//
//            if (CollectionUtils.isEmpty(taskList)) {
//                userTaskCountVo.setCount(0);
//            } else {
//                userTaskCountVo.setCount(taskList.size());
//            }
//
//            return userTaskCountVo;
//        }).sorted((o1, o2) -> o1.getCount() - o2.getCount()).limit(1).collect(Collectors.toList());
//
//
//        return countVoList.get(0).getUserId();
//    }
}
